import * as React from 'react';
import Collapse from 'antd/es/collapse/Collapse';
import { RouteComponentProps } from 'react-router';
import { inject, observer, Observer } from 'mobx-react';
import { FriendStore } from '../../store/FriendStore';
import { ChatStore } from '../../store/ChatStore';
import { GroupStore } from '../../store/GroupStore';
import { TagGroupStore } from '../../store/TagGroupStore';
import { NavLink } from 'react-router-dom';
import { FriendItem } from '../../interface/IFriend';
import { GroupItem, VirualGroupItem, VirualGroupMember } from '../../interface/IGroup';
import './group.less';
import { AvatorWithPhoto } from '../../component/avatorWithPhoto/AvatorWithPhoto';
import { ChatGrOrFrType } from '../../interface/IChat';
import { MainStore,detailType } from '../../store/MainStore';
import { tr } from '../../i18n/tr';
import { RequestStore } from '../../store/RequestStore';
import { List as VList } from 'react-virtualized/dist/es/List';
import { AutoSizer } from 'react-virtualized/dist/es/AutoSizer';
import { CellMeasurer, CellMeasurerCache } from 'react-virtualized/dist/es/CellMeasurer';
import deviceManager from '../../net/DeviceManager';
import Badge from 'antd/es/badge';
import UserSearch from '../../component/UserSearch/UserSearch';
import { Dropdown, Icon, Input, message, Tooltip, Menu } from 'antd';
import Modal from 'antd/es/modal';
import { UserGroupStore } from '../../store/UserGroupStore';
import SvgIcon from '../../component/svgIcon/SvgIcon';
import { set } from 'js-cookie';
import { SelectFriend } from '../../component/selectFriend/SelectFriend';
import systemStore from '../../store/SystemStore';
const Panel = Collapse.Panel;

export interface IGroupProps extends RouteComponentProps {
	noRead: number;
}
interface WithStoreGroup extends IGroupProps {
	friendStore: FriendStore;
	chatStore: ChatStore;
	groupStore: GroupStore;
	tagGroupStore: TagGroupStore;
	userGroupStore:UserGroupStore;
	mainStore: MainStore;
	requestStore: RequestStore;
}
export interface IGroupState {
	openKeys: string[];
	fHeights: any[];
	// friends: FriendItem[],
	// groups: GroupItem[],
	gHeights: any[];
	// 快速编辑数据
	groupEditing:{ show:boolean, edit:boolean, id?:string, value?:any,type:'group'|'tag'}
	/**
	 * 当前操作的分组
	 */
	group:VirualGroupItem,
	groupMemberEditing:{ show:boolean, value?:any,type:'group'|'tag'}
	groupItemContext:{
		menuShow:boolean,
		x?:number,y?:number
	}
}
@inject('friendStore', 'chatStore', 'groupStore', 'tagGroupStore','userGroupStore','mainStore', 'requestStore')
@observer
export default class GroupView extends React.Component<IGroupProps, IGroupState> {
	constructor(props: IGroupProps) {
		super(props);

		this.state = {
			openKeys: ['friend'],
			fHeights: [],
			gHeights: [],
			groupEditing : {
				show:false,
				edit:false,
				type:'group',
				value:''
			},
			group:null,
			groupMemberEditing:{
				show:false,
				type:'group'
			},
			groupItemContext:{
				menuShow:false,
				x:0,y:0
			}
			// friends: [],
			// groups: [],
		};
		this.refContextMenuDropDown = React.createRef();
	}
	refContextMenuDropDown = null
	rootSubmenuKeys = ['request', 'group', 'friend'];
	get injected() {
		return this.props as WithStoreGroup;
	}
	get chatDetail() {
		return this.injected.chatStore.currentChatData.extendInfo || {}
	}

	onOpenChange = (openKeys: string[]) => {
		const latestOpenKey = openKeys.find((key) => this.state.openKeys.indexOf(key) === -1);
		if (latestOpenKey && this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
			this.setState({ openKeys });
		} else {
			this.setState({
				openKeys: latestOpenKey ? [latestOpenKey] : []
			});
		}
	};

	onClick = (id: string) => {
		this.injected.chatStore.changeSelectChat(id);
	};

	// goFriendChat = (friend: FriendItem) => {
	// 	this.injected.chatStore.changeCurrentChat(friend);
	// };
	goFriendChat = (friend: FriendItem|VirualGroupMember) => {
		// 在这里插入一个 好友信息的页面
		this.injected.mainStore.showFriendInfo(detailType.messageGroup,friend);
	};

	goGroupChat = (group: GroupItem) => {
		this.injected.chatStore.changeCurrentChat_group(group);
	};

	showRequest = () => {
		this.injected.chatStore.goNewFriend();
		deviceManager.sendUpdateSelfInfoMsg();
		this.injected.requestStore.readRequest();
	};
	showRequestTags = ()=>{
		this.injected.friendStore.goTags();
	}

	measureFriendCache = new CellMeasurerCache({
		fixedWidth: true,
		minHeight: 100
	});

	measureGroupCache = new CellMeasurerCache({
		fixedWidth: true,
		minHeight: 100
	});

	getFHeight = (data: { index: number }) => {
		const row = this.state.fHeights.find((item) => item.index == data.index);
		return row ? row.height : 100;
	};

	getGHeight = (data: { index: number }) => {
		const row = this.state.gHeights.find((item) => item.index == data.index);
		return row ? row.height : 100;
	};

	hideMenu = (e:Event)=>{
		// let ref = this.refContextMenuDropDown;
		// if( ref && ref.contains(e.target)){
		// 	document.body.removeEventListener('mouseup', this.hideMenu)
		// 	return;
		// }else{
		// 	this.setState({
		// 		groupItemContext:{
		// 			menuShow:false,
		// 		}
		// 	})
		// }
		// document.body.removeEventListener('mouseup', this.hideMenu)
	}

	public render() {
		let groups:any = this.injected.groupStore.groupList;
		let tagGroups:VirualGroupItem[] = this.injected.tagGroupStore.groupList;
		let userGroups:VirualGroupItem[] = this.injected.userGroupStore.groupList;
		let friends = this.injected.friendStore.friendList;
		const filterText = this.injected.mainStore.filterTxt
		if( filterText ){
			groups = groups.filter(item => {
				let name = item.name;
				return name.indexOf(filterText) > -1

			});
			friends = friends.filter(item => {
				let name = item.toNickname;
				return name.indexOf(filterText) > -1
				
			})
		}
		// let groups = this.injected.groupStore.groupList
		// 	.filter((item) => {
		// 		const fileText = this.injected.mainStore.filterTxt;
		// 		if (!fileText) {
		// 			return true;
		// 		}
		// 		if (item.name.indexOf(fileText) > -1) {
		// 			return true;
		// 		}
		// 		return false;
		// 	})
		// 	.slice();

		// let friends = this.injected.friendStore.friendList
		// 	.filter((item) => {
		// 		const fileText = this.injected.mainStore.filterTxt;
		// 		if (!fileText) {
		// 			return true;
		// 		}
		// 		if (
		// 			(item.remarkName && item.remarkName.indexOf(fileText) > -1) ||
		// 			(item.toNickname && item.toNickname.indexOf(fileText) > -1)
		// 		) {
		// 			return true;
		// 		}
		// 		return false;
		// 	})
		// 	.slice();

		const renderItemGroup = ({ index, key, parent, style }: any) => {
			return <div>11</div>
			return (
				<CellMeasurer
					cache={this.measureGroupCache}
					key={key}
					parent={parent}
					columnIndex={index}
					bordered={false}
				>
					{/* <Menu.Item key={groups[data.index].id}> */}

					<NavLink
						style={style}
						to={`${this.props.match.url}/${groups[index].id}`}
						onClick={() => this.goGroupChat(groups[index])}
						activeClassName="selected"
						className="list-new-item"
					>
						<AvatorWithPhoto 
						size={40}
						type={ChatGrOrFrType.group} 
						id={groups[index].jid} classN="userphoto"
						 />
						<span className="item-right friend-name">{groups[index].name}</span>
					</NavLink>
					{/* </Menu.Item> */}
				</CellMeasurer>
			);
		};

		const renderGroups = ()=>{
			return groups.map((item,index)=>{
				return (
					<NavLink
						to={`${this.props.match.url}/${groups[index].id}`}
						onClick={() => this.goGroupChat(groups[index])}
						activeClassName="selected"
						className="list-new-item"
					>
						<AvatorWithPhoto 
						forceUpdate={false}
						userType={item.userType || item.toUserType}
						size={40}
						type={ChatGrOrFrType.group} 
						id={groups[index].jid} classN="userphoto"
						 />
						<span className="item-right friend-name">{groups[index].name}</span>
					</NavLink>
				);	
			})
		}
		const renderTagGroups = ()=>{
			return tagGroups.map((group,index)=>{
				return (
					<Panel header={`${group.name}(${group.members.length})`} key={'tag-group-'+index} extra={
						<div className='option'>
							<Icon type="delete" onClick={(e)=>{
								e.stopPropagation();
								if( group.members.length > 0){
									Modal.confirm({
										title: '标签里面存在用户，确定删除吗？',
										okText: '确定',
										cancelText: '取消',	
										onOk: ()=>{
											this.injected.tagGroupStore.removeTagGroup(group.name);
										}
									})
								}else{
									this.injected.tagGroupStore.removeTagGroup(group.name);
								}
								
							}} />
						</div>
					}>
						{ 
							group.members.map((item ,index)=>{
								const user = item as VirualGroupMember;
								
								return (
									<NavLink
										key={item.userId}
										to={`${this.props.match.url}/${user.userId}`}
										onClick={() => this.goFriendChat(user)}
										activeClassName="selected"
										className="list-new-item"
									>
										<AvatorWithPhoto 
										forceUpdate={false}
										size={40}
										type={ChatGrOrFrType.friend} 
										id={user.userId} classN="userphoto"
										/>
										<span className="item-right friend-name">{user.nickname || user.name}</span>
									</NavLink>
								)
							})
					  }
						
					</Panel>
				);	
			})
		}
		const renderUserGroups = ()=>{
			return userGroups.map((group,index)=>{
				return (
					<Panel header={<div onContextMenu={e=>{
								
						e.preventDefault(); // 阻止默认右键菜单
						this.setState({
						 group,
						 groupItemContext:{
							 menuShow:true,
							 x:e.clientX,
							 y:e.clientY,
						 }
						})

				 }}>{ group.name }({group.members.length})</div>} key={'user-group-'+index}>
						{ 
							group.members.map((item ,index)=>{
								const user = item as VirualGroupMember;
								
								return (
									<NavLink
										key={item.userId}
										to={`${this.props.match.url}/${user.userId}`}
										onClick={() => {
											if( isMe(item)){
												return;
											}
											this.goFriendChat(user)
										}}
										activeClassName="selected"
										className="list-new-item"
									>
										
										<AvatorWithPhoto 
										forceUpdate={false}
										size={40}
										type={ChatGrOrFrType.friend} 
										userType={item.userType || item.toUserType}
										onlineStyle='dot'
										onlinestate={user.onlinestate}
										id={user.toUserId} classN="userphoto"
										/>
										<span className="item-right friend-name">{user.toNickname || user.nickname || user.name}  {isMe(item)?`(我)`:''}</span>
										<span className='opt'>
											<Tooltip title="移除分组成员">
												<span onClick={(e)=>{
													e.stopPropagation();
													this.injected.userGroupStore.removeUserGroupUser(user.toUserId,group.name);
													message.success('操作成功');
												}}> <SvgIcon name='group-remove-user' size='12'></SvgIcon></span>
											</Tooltip>
										</span>
									</NavLink>
								)
							})
					  }
						
					</Panel>
				);	
			})
		}
		const isMe = (item)=>{
			const userId = item.toUserId;
			return userId == systemStore.user.userId
		}
		const renderFriends = ()=>{
			return friends.map((item,index)=>{
				return (
					<NavLink
						to={`${this.props.match.url}/${friends[index].toUserId}`}
						onClick={() => {
							if( isMe(item)){
								return;
							}
							this.goFriendChat(friends[index])
						}}
						activeClassName="selected"
						className="list-new-item"
						key={index}
					>
						<AvatorWithPhoto
							size={40}
							type={ChatGrOrFrType.friend}
							id={friends[index].toUserId + ''}
							userType={item.userType || item.toUserType}
							onlineStyle={'dot'}
							onlinestate={friends[index].onlinestate}
							classN="head userphoto"
						/>
						<span className="item-right friend-name">
							{friends[index].remarkName || friends[index].toNickname} {isMe(item)?`(我)`:''}
						</span>
					</NavLink>
				);	
			})
		}
		const renderItemFriend = ({ index, key, parent, style }: any) => {
			return (
				<CellMeasurer
					cache={this.measureFriendCache}
					columnIndex={index}
					key={`${this.props.match.url}/${friends[index].toUserId}`}
					parent={parent}
					bordered={false}
				>
					{/* <Menu.Item key={friends[data.index].toUserId}> */}
					<NavLink
						style={style}
						to={`${this.props.match.url}/${friends[index].toUserId}`}
						onClick={() => this.goFriendChat(friends[index])}
						activeClassName="selected"
						className="list-new-item"
					>
						<AvatorWithPhoto
							size={40}
							type={ChatGrOrFrType.group}
							id={friends[index].toUserId + ''}
							classN="head userphoto"
						/>
						<span className="item-right friend-name">
							{friends[index].remarkName || friends[index].toNickname}
						</span>
					</NavLink>
					{/* </Menu.Item> */}
				</CellMeasurer>
			);
		};

		const renderQuickEditModal =()=>{
			const info = this.state.groupEditing
			return (
				<div>
					<Modal
						title={info.type == 'group'?`${info.edit?'编辑':'添加'}用户分组`:`${info.edit?'编辑':'添加'}用户标签`}
						visible={this.state.groupEditing.show}
						cancelText="取消"
						okText="确定"
						onOk={()=>{
							const info = this.state.groupEditing
							const groups = info.type == 'group'?this.injected.userGroupStore.groupList:this.injected.tagGroupStore.groupList;
							if( !info.edit ){
								if( groups.find(item=>item.name == info.value)){
									Modal.error({
										title:'分组名或标签重复'
									})
									return;
								}
								if( info.type == 'group'){
									this.injected.userGroupStore.createUserGroup(info.value);
									
								}else{
									this.injected.tagGroupStore.createTagGroup(info.value);
								}
								
							}else{
								if( info.type == 'group'){
									this.injected.userGroupStore.updateGroupInfo(info.id, info.value);
								}
							}
							this.setState({
								groupEditing:{
									show:false,
									edit:false,
									type:'group',
								}
							})
						}}
						onCancel={()=>{
							this.setState({
								groupEditing:{
									show:false,
									edit:false,
									type:'group',
								}
							})
						}}
					>
						<div>
							<Input value={info.value} placeholder='填写分组名称' onChange={(e)=>{
								this.setState({
									groupEditing:{
										...info,
										value:e.target.value
									}
								})
							}} />
						</div>
					</Modal>
				</div>
			)
		}
		
		const renderQuickEditMemberModal = ()=>{
			const info = this.state.groupMemberEditing
			return (
				<div>
					<Modal
						title={info.type == 'group'?`编辑分组成员`:`编辑标签成员`}
						visible={info.show}
						cancelText="取消"
						okText="确定"
						onOk={()=>{
							
							this.setState({
								groupMemberEditing:{
									show:false,
									type:'group',
								}
							})
						}}
						onCancel={()=>{
							this.setState({
								groupMemberEditing:{
									show:false,
									type:'group',
								}
							})
						}}
					>
						<div>
							<Input value={info.value} onChange={(e)=>{
								this.setState({
									groupMemberEditing:{
										...info,
										value:e.target.value
									}
								})
							}} />
						</div>
					</Modal>
				</div>
			)
		}
		
		const menu = (
			// <div ref={ref=>this.refContextMenuDropDown = ref}>
				<Menu
					
					selectedKeys={this.state.openKeys}
					onOpenChange={this.onOpenChange}
					mode="inline"
					onClick={({ key }) => {
						const group = this.state.group;
						switch(key){
							case 'add':
								this.setState({
									groupEditing:{
										show:true,
										edit:false,
										type:'group',
										value:''
									}
								})
								break;
							case 'edit-title':
								this.setState({
									groupEditing:{
										show:true,
										edit:true,
										type:'group',
										id:this.state.group.id,
										value:this.state.group.name
									}
								})
								break;
							case 'edit':
								this.setState({
									groupMemberEditing:{
										show:true,
										type:'group',
										value:group.name
									}
								})
								break;
							case 'delete':
								if( !group ){
									message.error('请选择一个分组');
									return;
								}
								if( group.members.length > 0){
									Modal.confirm({
										title: '用户组里面存在用户，确定删除吗？',
										okText: '确定',
										cancelText: '取消',	
										onOk: ()=>{
											this.injected.userGroupStore.removeUserGroup(group.name);
										}
									})
								}else{
									this.injected.userGroupStore.removeUserGroup(group.name);
								}
								break;
						}
						this.setState({
							groupItemContext:{
								menuShow:false,
							}
						})
						//setContextMenu(null); // 关闭菜单
					}}
				>
					<Menu.Item key="add">新建分组</Menu.Item>
					{ this.state.group ? <Menu.Item key="edit-title">修改名称</Menu.Item> :null }
					{ this.state.group ? <Menu.Item key="edit">编辑成员</Menu.Item> :null }
					{ this.state.group ? <Menu.Item key="delete">删除分组</Menu.Item> :null }
				</Menu>
			// </div>
		);
		
		const members = this.state.group?this.state.group.members:[];
		let friendList = this.injected.friendStore.friendList.concat().map(item=>{
			return {
				...item, 
				isSelected: members.find(m=>m.toUserId == item.toUserId+'')!=null
			}
		})
		// 好友的列表目前不是全量的
		const groupsFriends = this.injected.userGroupStore.groupList.map(item=>{
			let members:any = item.members || []
			friendList = friendList.concat(members)
		})
		friendList = friendList.map(item=>{
			return {
				...item, 
				isSelected: members.find(m=>m.toUserId == item.toUserId+'')!=null
			}
		})
		return (
			<div className="chart-list chart-list-group">
				<UserSearch></UserSearch>
				{ renderQuickEditModal()}
				{this.state.groupMemberEditing.show ? (
						<SelectFriend
							title="选择好友1"
							confirmText='确定'
							isShow={this.state.groupMemberEditing.show}
							selectConfirm={(list:FriendItem[])=>{
								this.injected.userGroupStore.updateGroupUsers(this.state.groupMemberEditing.value,list.map(item=> item.toUserId+''),members.map(item=> item.toUserId+''));
								//this.injected.userGroupStore.addUsersGroup(list.map(item=> item.toUserId+''),this.state.groupMemberEditing.value);
								this.setState({
									groupMemberEditing:{
										show:false,type:'group'
									}
								})
							}}
							cancel={()=>{
								this.setState({
									groupMemberEditing:{
										show:false,type:'group'
									}
								})
							}}
							friendList={friendList}
						/>
					) : null}

				<div className='accordion-wrapper'>
					<div onClick={this.showRequest} className="list-item">
						<span className="name ">
							<SvgIcon name="friends" size='30'></SvgIcon><Badge dot={this.injected.requestStore.haveUnreadReq > 0} style={{zIndex:1}}>新的朋友</Badge>
						</span>
					</div>
					<div onClick={this.showRequestTags} className="list-item name-bot">
						<span className="name">
							<SvgIcon name="tags" size='30'></SvgIcon><Badge style={{zIndex:1}}>用户标签</Badge>
						</span>
					</div>
				<div className="chat-list-group">
					<div className='chat-list-group-item'>
						{/* <h3 className='chat-list-group-title'>我的群聊</h3> */}
						<Collapse defaultActiveKey={['2']} accordion={false} bordered={false} >
							<Panel header={`我的群组(${groups.length})`} key="1" id="contact-newfriend-list" forceRender={false}>
							{ renderGroups()}
							</Panel>
							<Panel header={<div onContextMenu={e=>{
								
								 e.preventDefault(); // 阻止默认右键菜单
								 this.setState({
									group:null,
									groupItemContext:{
										menuShow:true,
										x:e.clientX,
										y:e.clientY,
									}
								 })

							}}>未分组好友({friends.length})</div>} key="2" id="contact-myfriend-list" forceRender={false}>
							{/* <AutoSizer>
								{({ width, height }) => (
									<VList
										rowHeight={60}
										width={width}
										height={height}
										overscanRowCount={10}
										rowCount={friends.length}
										rowRenderer={({ ...props }) => (
											<Observer key = {props.key}>
												{() => {
													return renderItemFriend({ ...props })
												}}
											</Observer>
											)}
									/>
								)}
							</AutoSizer> */}
							{ renderFriends()}
						</Panel>
						{ renderUserGroups() }
						</Collapse>
					</div>
					
					{/* <div className='chat-list-group-item'>
						<h3 className='chat-list-group-title'>
							<span>我的标签</span>
							<span className='action'>
								<Tooltip title="新建标签">
									<span  onClick={()=>{
										this.setState({
											groupEditing:{
												show:true,
												edit:false,
												type:'tag',
												value:''
											}
										})
									}}>
										<SvgIcon name="group-add2" size='14'></SvgIcon>
									</span>
								</Tooltip>
								
							</span>
						</h3>
						<Collapse defaultActiveKey={['4']} accordion={false} bordered={false} >
							{
								renderTagGroups()
							}
						</Collapse>
					</div> */}
					{
						<Dropdown overlay={menu} onVisibleChange={visible=>{
							if(!visible){
								this.setState({
									groupItemContext:{
										menuShow:false,
									}
								})
								
							}
						}} visible={this.state.groupItemContext.menuShow} trigger={['contextMenu']} placement="bottomLeft">
						<div
							 
							style={{
								position: 'absolute',
								top: this.state.groupItemContext.y,
								left: this.state.groupItemContext.x,
								width: 0,
								height: 0,
							}}
						/>
					</Dropdown>
					}
					
				</div>

					
				</div>
				
				
			</div>
		);
	}
}
